package com.bsoft.gol.editor.service.impl;
import ctd.controller.exception.ControllerException;
import ctd.util.BeanUtils;
import com.bsoft.gol.editor.dao.*;
import com.bsoft.gol.editor.editor.*;
import com.bsoft.gol.editor.editor.request.CollectTitleRequest;
import com.bsoft.gol.editor.editor.request.GetQuestionnaireDetailRequest;
import com.bsoft.gol.editor.editor.request.QueryCollectionListRequest;
import com.bsoft.gol.editor.editor.response.*;
import hcn.util.BaseResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.bsoft.gol.editor.service.EditorQuestionnaireTitleApi;
import com.bsoft.gol.editor.utils.CommonUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static org.springframework.beans.BeanUtils.copyProperties;


/**
 * 表单题目表
 */
@Service("editorQuestionnaireTitleApi")
@Transactional
public class EditorQuestionnaireTitleApiImpl implements EditorQuestionnaireTitleApi {
    private static Logger logger = LoggerFactory.getLogger(EditorQuestionnaireTitleApiImpl.class);
    @Autowired
    private EditorQuestionnaireTitleDAO editorQuestionnaireTitleDAO;
    @Autowired
    private EditorTitleOptionDAO editorTitleOptionDAO;
    @Autowired
    private EditorDisplayLogicDAO editorDisplayLogicDAO;
    @Autowired
    private EditorSkipLogicDAO editorSkipLogicDAO;
    @Autowired
    private EditorQuestionnaireStyleDAO editorQuestionnaireStyleDAO;
    @Autowired
    private EditorQuestionnaireDAO editorQuestionnaireDAO;
    @Autowired
    private EditorUserInfoDAO editorUserInfoDAO;
    @Autowired
    private EditorAnswerDAO editorAnswerDAO;
    @Autowired
    private EditorDictDAO editorDictDAO;
    @Autowired
    private EditorQuestionnaireTitleCollectionDAO editorQuestionnaireTitleCollectionDAO;





    /**
     * 题目新增
     * @param editorQuestionnaireTitle
     * @return
     */
    @Override
    public EditorQuestionnaireTitle add(EditorQuestionnaireTitle editorQuestionnaireTitle) throws ControllerException {
        if(CommonUtils.isNotEmpty(editorQuestionnaireTitle.getTitleId())){
            EditorQuestionnaireTitle title = editorQuestionnaireTitleDAO.get(editorQuestionnaireTitle.getTitleId());
            if(null != title){
                return operateCopy(editorQuestionnaireTitle.getOrderNum(), editorQuestionnaireTitle.getQuestionnaireId(), title);
            }else {
                throw new ControllerException("该问卷题目不存在");
            }

        }else {
            EditorQuestionnaireTitle resp = new EditorQuestionnaireTitle();
            editorQuestionnaireTitle.setTitleId(UUID.randomUUID().toString().replaceAll("-", ""));
            //修改排序号、题号    获取大于等于当前排序号的题目  (排序号大于等于题号)
            List<EditorQuestionnaireTitle> editorQuestionnaireTitleResList = editorQuestionnaireTitleDAO.queryEditorQuestionnaireTitleByOrderNum(editorQuestionnaireTitle.getOrderNum(),editorQuestionnaireTitle.getQuestionnaireId());
            if(editorQuestionnaireTitleResList.size()>0){
                //循环获取题目，并题号加1操作
                for(EditorQuestionnaireTitle res: editorQuestionnaireTitleResList ){
                    res.setOrderNum(res.getOrderNum()+1);
                    res.setTitleNum(res.getTitleNum()+1);
                    if(CommonUtils.isNotEmpty(res.getTitleNum())&&CommonUtils.isNotEmpty(res.getOrderNum())) {
                        editorQuestionnaireTitleDAO.updateEditorQuestionnaireTitleOrder(res.getTitleId(), res.getOrderNum(), res.getTitleNum());
                    }
                }
            }

            logger.info(editorQuestionnaireTitle.getTitleId());
            Date now = new Date();
            editorQuestionnaireTitle.setCreateTime(now);
            //设置问卷题目默认值
            setDefaultTitleValue(editorQuestionnaireTitle);
            editorQuestionnaireTitleDAO.save(editorQuestionnaireTitle);
            resp.setTitleId(editorQuestionnaireTitle.getTitleId());
            return resp;
        }
    }

    private void setDefaultTitleValue(EditorQuestionnaireTitle title){
        if(CommonUtils.isEmpty(title.getUploadFilesizeLimit())){
            title.setUploadFilesizeLimit("5");
        }
        if(CommonUtils.isEmpty(title.getTitleReturn())){
            title.setTitleReturn((byte) 2);
        }
        if(CommonUtils.isEmpty(title.getLayout())){
            title.setLayout((byte) 1);
        }
        if(CommonUtils.isEmpty(title.getDataFormat())){
            title.setDataFormat(1);
        }
        if(CommonUtils.isEmpty(title.getOptionModifyFlag())){
            title.setOptionModifyFlag((byte) 2);
        }
        if(CommonUtils.isEmpty(title.getDictSelectMethod())){
            title.setDictSelectMethod((byte) 2);
        }
        if(CommonUtils.isEmpty(title.getCanAddRow())){
            title.setCanAddRow(2);
        }
    }

    /**
     * 题目修改
     * @param editorQuestionnaireTitleReq
     */
    @Override
    public void update(EditorQuestionnaireTitle editorQuestionnaireTitleReq) {
        EditorQuestionnaireTitle editorQuestionnaireTitle = editorQuestionnaireTitleDAO.get(editorQuestionnaireTitleReq.getTitleId());
        BeanUtils.copy(editorQuestionnaireTitleReq,editorQuestionnaireTitle);
        EditorQuestionnaireTitle questionnaireTitle = editorQuestionnaireTitleDAO.get(editorQuestionnaireTitleReq.getTitleId());
        if(questionnaireTitle.getTitleNum()!=0&&("1".equals(questionnaireTitle.getRegion())|| "3".equals(questionnaireTitle.getRegion()))) {
            List<EditorQuestionnaireTitle> editorQuestionnaireTitleResList = editorQuestionnaireTitleDAO.queryEditorQuestionnaireTitleByOrderNumD(questionnaireTitle.getTitleNum(), questionnaireTitle.getQuestionnaireId());
            //大于当前题号的，都做减1操作
            if (editorQuestionnaireTitleResList.size() > 0) {
                //循环获取题目，并题号减1操作
                for (EditorQuestionnaireTitle res : editorQuestionnaireTitleResList) {
                    EditorQuestionnaireTitle req = new EditorQuestionnaireTitle();
                    req.setTitleId(res.getTitleId());
//                    req.setOrderNum(res.getOrderNum() - 1);
                    if (res.getTitleNum() != 0 && questionnaireTitle.getTitleNum() != 0) {
                        req.setTitleNum(res.getTitleNum() - 1);
                    } else {
                        req.setTitleNum(res.getTitleNum());
                    }

                    editorQuestionnaireTitleDAO.updateEditorQuestionnaireTitleTitleNum(req.getTitleId(),req.getTitleNum());
                }
            }
            editorQuestionnaireTitle.setTitleNum(0);
        }
        editorQuestionnaireTitleDAO.update(editorQuestionnaireTitle);
    }

    /**
     * 题目删除
     * @param editorQuestionnaireTitleReq
     */
    @Override
    public void delete(EditorQuestionnaireTitle editorQuestionnaireTitleReq) {
        List<EditorQuestionnaireTitle> editorQuestionnaireTitleResList=null;
        //获取题目信息
        EditorQuestionnaireTitle questionnaireTitle = editorQuestionnaireTitleDAO.get(editorQuestionnaireTitleReq.getTitleId());

        editorQuestionnaireTitleResList = editorQuestionnaireTitleDAO.queryEditorQuestionnaireTitleByOrderNumD(questionnaireTitle.getOrderNum(),questionnaireTitle.getQuestionnaireId());
        //大于当前题号的，都做减1操作
        if(editorQuestionnaireTitleResList.size()>0){
            //循环获取题目，并题号减1操作
            for(EditorQuestionnaireTitle res: editorQuestionnaireTitleResList ){
                EditorQuestionnaireTitle req = new EditorQuestionnaireTitle();
                req.setTitleId(res.getTitleId());
                req.setOrderNum(res.getOrderNum()-1);
                req.setTitleNum(res.getTitleNum() - 1);

                editorQuestionnaireTitleDAO.updateEditorQuestionnaireTitleOrder(req.getTitleId(),req.getOrderNum(),req.getTitleNum());
            }
        }
        editorQuestionnaireTitleDAO.remove(editorQuestionnaireTitleReq.getTitleId());
        //预留删除题目关联表数据
        //删除选项
        editorTitleOptionDAO.removeByTitleId(editorQuestionnaireTitleReq.getTitleId());
        //删除逻辑表
        editorDisplayLogicDAO.removeByTitleId(editorQuestionnaireTitleReq.getTitleId());
        //删除跳题表
        editorSkipLogicDAO.removeByTitleId(editorQuestionnaireTitleReq.getTitleId());
    }
//
    /**
     * 复制题目信息
     * @param editorQuestionnaireTitleReq
     * @return
     */
    @Override
    public EditorQuestionnaireTitle copyTitle(EditorQuestionnaireTitle editorQuestionnaireTitleReq) {
        //获取题目信息
        EditorQuestionnaireTitle questionnaireTitle = editorQuestionnaireTitleDAO.get(editorQuestionnaireTitleReq.getTitleId());
        return operateCopy(questionnaireTitle.getOrderNum(),questionnaireTitle.getQuestionnaireId(),questionnaireTitle);
    }

    /**
     * @description: 复制某个题目到问卷里
     * @author: chenJij@bsoft.com.cn
     * @date: 2021/11/5 15:28
     * @param: orderNum 当前题目的序号
     * @param: questionnaireId 问卷标识
     * @param: questionnaireTitle 问卷题目对象
     * @return: com.bsoft.gol.editor.editor.EditorQuestionnaireTitle 返回问卷题目对象
     */
    private EditorQuestionnaireTitle operateCopy(Integer orderNum, String questionnaireId, EditorQuestionnaireTitle questionnaireTitle) {

        EditorQuestionnaireTitle editorQuestionnaireTitle = new EditorQuestionnaireTitle();
        List<EditorQuestionnaireTitle> editorQuestionnaireTitleResList=null;
        editorQuestionnaireTitleResList = editorQuestionnaireTitleDAO.queryEditorQuestionnaireTitleByOrderNumD(orderNum,questionnaireId);//大于当前排序号
        //大于当前题号的，都做加1操作
        if(editorQuestionnaireTitleResList.size()>0){
            //循环获取题目，并题号加1操作
            for(EditorQuestionnaireTitle res: editorQuestionnaireTitleResList ){
                EditorQuestionnaireTitle req = new EditorQuestionnaireTitle();
                req.setTitleId(res.getTitleId());
                req.setOrderNum(res.getOrderNum()+1);
                if(res.getTitleNum()!=0) {
                    req.setTitleNum(res.getTitleNum() + 1);
                }else {
                    //防止下次减一的时候报空指针
                    req.setTitleNum(res.getTitleNum());
                }
                editorQuestionnaireTitleDAO.updateEditorQuestionnaireTitleOrder(req.getTitleId(),req.getOrderNum(),req.getTitleNum());
            }
        }
        //复制题目信息 新增题目
        EditorQuestionnaireTitle title = new EditorQuestionnaireTitle();
        copyProperties(questionnaireTitle,title);
        title.setQuestionnaireId(questionnaireId);
        title.setTitleId(UUID.randomUUID().toString().replaceAll("-", ""));
        title.setOrderNum(questionnaireTitle.getOrderNum()+1);
        if(questionnaireTitle.getTitleNum()!=0){
            title.setTitleNum(questionnaireTitle.getTitleNum()+1);
        }else{
            title.setTitleNum(questionnaireTitle.getTitleNum());
        }
        Date now = new Date();
        title.setCreateTime(now);
        editorQuestionnaireTitleDAO.save(title);
        //复制选项信息 新增选项
        List<EditorTitleOption> optionList =  editorTitleOptionDAO.queryEditorTitleOptionByTitleId(questionnaireTitle.getTitleId());
        String optionIds ="";
        if(optionList.size()>0){
            for(EditorTitleOption option:optionList){
                EditorTitleOption titleOption = new EditorTitleOption();
                copyProperties(option,titleOption);
                titleOption.setTitleId(title.getTitleId());
                titleOption.setOptionId(UUID.randomUUID().toString().replaceAll("-", ""));
                Date optionNow = new Date();
                titleOption.setCreateTime(optionNow);
                editorTitleOptionDAO.save(titleOption);
                optionIds +=titleOption.getOptionId()+",";
            }
            if(!"".equals(optionIds)){
                optionIds = optionIds.substring(0,optionIds.length()-1);
            }
        }
        editorQuestionnaireTitle.setTitleId(title.getTitleId());
        editorQuestionnaireTitle.setOptionIds(optionIds);
        List<EditorQuestionnaireTitle> editorQuestionnaireTitles = editorQuestionnaireTitleDAO.queryEditorQuestionnaireTitleByOrderNumLow(orderNum-1,questionnaireId);
        if (CommonUtils.isNotEmpty(editorQuestionnaireTitles)){
            for (EditorQuestionnaireTitle res : editorQuestionnaireTitles) {
                if (res.getWidgetType()==10||res.getWidgetType()==11||res.getWidgetType()==12){
                    res.setOrderNum(res.getOrderNum()+1);
                    if(res.getTitleNum()!=0) {
                        res.setTitleNum(res.getTitleNum() + 1);
                    }
                    if(CommonUtils.isNotEmpty(res.getTitleNum())&&CommonUtils.isNotEmpty(res.getOrderNum())) {
                        editorQuestionnaireTitleDAO.updateEditorQuestionnaireTitleOrder(res.getTitleId(), res.getOrderNum(), res.getTitleNum());
                    }
                }
            }
        }
        return editorQuestionnaireTitle;
    }

    /**
     * 修改题号
     * @param editorQuestionnaireTitleReq
     */
    @Override
    public void updateTitleNum(EditorQuestionnaireTitle editorQuestionnaireTitleReq) {
        editorQuestionnaireTitleReq.getPreOrderNum();//拖动前排序号
        editorQuestionnaireTitleReq.getAfterOrderNum();//拖动后排序号
        List<EditorQuestionnaireTitle> editorQuestionnaireTitleResList=null;


        List<EditorQuestionnaireTitle> afterTitles = new ArrayList<>();
        //按照顺序查出全部的题目
        List<EditorQuestionnaireTitle> titles = editorQuestionnaireTitleDAO.queryEditorQuestionnaireTitleByQid(editorQuestionnaireTitleReq.getQuestionnaireId());
        if (CommonUtils.isNotEmpty(titles)) {
            //换序前的序号
            Integer preOrderNum = editorQuestionnaireTitleReq.getPreOrderNum();
            //换序后的序号
            Integer afterOrderNum = editorQuestionnaireTitleReq.getAfterOrderNum();
            //换序前的对象
            EditorQuestionnaireTitle questionnaireTitle = titles.get(preOrderNum - 1);
            //最终结果序号
            int sort = 1;
            for (int j = 1; j <= titles.size(); j++) {
                EditorQuestionnaireTitle title = titles.get(j - 1);
                //跳过换序前的对象
                if (preOrderNum != j) {
                    //当最终结果序号和换序后的序号一致时，添加换序前的对象，并自增序号
                    if (afterOrderNum == sort) {
                        questionnaireTitle.setOrderNum(sort);
                        questionnaireTitle.setTitleNum(sort);
                        afterTitles.add(questionnaireTitle);
                        sort++;
                    }
                    //逐个添加对象，序号自增
                    title.setOrderNum(sort);
                    title.setTitleNum(sort);

                    afterTitles.add(title);
                    sort++;
                }
            }

            for (EditorQuestionnaireTitle afterTitle : afterTitles) {
                editorQuestionnaireTitleDAO.updateEditorQuestionnaireTitleOrder(afterTitle.getTitleId(), afterTitle.getOrderNum(), afterTitle.getTitleNum());
            }
        }

//        //拖动前排序号大于拖动后排序号    拖动前题号大于拖动后题号
//        if(editorQuestionnaireTitleReq.getPreOrderNum()>editorQuestionnaireTitleReq.getAfterOrderNum()){
//            editorQuestionnaireTitleResList = editorQuestionnaireTitleDAO.queryEditorQuestionnaireTitleByAfterOrderNum(editorQuestionnaireTitleReq.getQuestionnaireId(),editorQuestionnaireTitleReq.getAfterOrderNum(),editorQuestionnaireTitleReq.getPreOrderNum());
//            if(editorQuestionnaireTitleResList.size()>0){
//                //循环获取题目，并排序号、题号加1操作
//                for(EditorQuestionnaireTitle res: editorQuestionnaireTitleResList ){
//                    EditorQuestionnaireTitle req = new EditorQuestionnaireTitle();
//                    req.setTitleId(res.getTitleId());
//                    req.setOrderNum(res.getOrderNum()+1);
//                    if(res.getTitleNum()!=0&&editorQuestionnaireTitleReq.getPreTitleNum()!=0&&editorQuestionnaireTitleReq.getAfterTitleNum()!=0) {
//                        req.setTitleNum(res.getTitleNum() + 1);
//                    }else{
//                        req.setTitleNum(res.getTitleNum());
//                    }
//                    editorQuestionnaireTitleDAO.updateEditorQuestionnaireTitleOrder(req.getTitleId(),req.getOrderNum(),req.getTitleNum());
//                }
//            }
//        }else{////拖动前题号小于拖动后题号
//            editorQuestionnaireTitleResList = editorQuestionnaireTitleDAO.queryEditorQuestionnaireTitleByPreOrderNumOrderNum(editorQuestionnaireTitleReq.getQuestionnaireId(),editorQuestionnaireTitleReq.getAfterOrderNum(),editorQuestionnaireTitleReq.getPreOrderNum());
//            if(editorQuestionnaireTitleResList.size()>0){
//                //循环获取题目，并题号减1操作
//                for(EditorQuestionnaireTitle res: editorQuestionnaireTitleResList ){
//                    EditorQuestionnaireTitle req = new EditorQuestionnaireTitle();
//                    req.setTitleId(res.getTitleId());
//                    req.setOrderNum(res.getOrderNum()-1);
//                    if(res.getTitleNum()!=0&&editorQuestionnaireTitleReq.getPreTitleNum()!=0&&editorQuestionnaireTitleReq.getAfterTitleNum()!=0) {
//                        req.setTitleNum(res.getTitleNum()-1);
//                    }else{
//                        req.setTitleNum(res.getTitleNum());
//                    }
//                    editorQuestionnaireTitleDAO.updateEditorQuestionnaireTitleOrder(req.getTitleId(),req.getOrderNum(),req.getTitleNum());
//                }
//            }
//        }
//        if(editorQuestionnaireTitleReq.getPreTitleNum()==0){
//            editorQuestionnaireTitleReq.setAfterTitleNum(0);
//        }
//        if(editorQuestionnaireTitleReq.getAfterTitleNum()==0){
//            editorQuestionnaireTitleReq.setAfterTitleNum(editorQuestionnaireTitleReq.getPreTitleNum());
//        }
//
    }
//
    /**
     * 添加选项
     * @param editorTitleOptionReq
     * @return
     */
    @Override
    public EditorTitleOption addOption(EditorTitleOption editorTitleOptionReq) {
        //设置默认值
        setDefaultTitleOption(editorTitleOptionReq);
        Date optionNow = new Date();
        editorTitleOptionReq.setCreateTime(optionNow);
        editorTitleOptionDAO.save(editorTitleOptionReq);
        return editorTitleOptionReq;
    }

    /**
     * 设置选项的默认值
     */
    private void setDefaultTitleOption(EditorTitleOption option){
        if(CommonUtils.isEmpty(option.getOptionAbnormal())){
            option.setOptionAbnormal(2);
        }
        if(CommonUtils.isEmpty(option.getOptionDataFormat())){
            option.setOptionDataFormat(1);
        }
        if(CommonUtils.isEmpty(option.getIsImport())){
            option.setIsImport(2);
        }
        if(CommonUtils.isEmpty(option.getColWidth())){
            option.setColWidth(150);
        }
    }
//
    /**
     * 修改选项
     * @param editorTitleOptionReq
     */
    @Override
    public void updateOption(EditorTitleOption editorTitleOptionReq) {
        EditorTitleOption editorTitleOption = editorTitleOptionDAO.get(editorTitleOptionReq.getOptionId());
        BeanUtils.copy(editorTitleOptionReq,editorTitleOption);
        editorTitleOption.setOptionIds(null);
        editorTitleOptionDAO.update(editorTitleOption);
    }

    /**
     * 修改选项号
     * @param editorTitleOptionReq
     */
    @Override
    public void updateOptionNum(EditorTitleOption editorTitleOptionReq) {
        EditorTitleOption editorTitleOption = editorTitleOptionDAO.get(editorTitleOptionReq.getOptionId());
        BeanUtils.copy(editorTitleOptionReq,editorTitleOption);

        editorTitleOptionDAO.update(editorTitleOption);

    }
//
    /**
     * 删除选项
     * @param editorTitleOptionReq
     */
    @Override
    public void deleteOption(EditorTitleOption editorTitleOptionReq) {
        //获取选项信息
        List<String> optionIds = Arrays.asList(editorTitleOptionReq.getOptionIds().split(","));
        Integer maxCol = 0;
        Integer maxRow=0;
        String titleId=null;

        for(String optionId : optionIds){
            EditorTitleOption editorTitleOption = editorTitleOptionDAO.get(optionId);
            titleId=editorTitleOption.getTitleId();
            if(editorTitleOption!=null) {
                List<EditorTitleOption> editorTitleOptionList = new ArrayList<>();

                if(CommonUtils.isNotEmpty(editorTitleOption.getOptionNum())) {
                    editorTitleOptionList = editorTitleOptionDAO.queryEditorTitleOptionByOptionNum(editorTitleOption.getOptionNum(), editorTitleOption.getTitleId());
                    //大于当前选项号的，都做减1操作
                    if (editorTitleOptionList.size() > 0) {
                        //循环获取选项，并选项号减1操作
                        for (EditorTitleOption res : editorTitleOptionList) {
                            EditorTitleOption req = new EditorTitleOption();
                            req.setOptionId(res.getOptionId());
                            req.setOptionNum(res.getOptionNum() - 1);
                            editorTitleOptionDAO.updateEditorTitleOptionOrder(req.getOptionId(), req.getOptionNum());
                        }
                    }
                }else if(CommonUtils.isNotEmpty(editorTitleOption.getColNum())){
                   if(editorTitleOption.getColNum()>maxCol){
                       maxCol=editorTitleOption.getColNum();
                   }
                   if(editorTitleOption.getRowNum()>maxRow){
                       maxRow=editorTitleOption.getRowNum();
                   }
                }
                editorTitleOptionDAO.remove(optionId);

                //删除跳题表

                editorSkipLogicDAO.removeByOptionId(optionId);
                //删除逻辑表

                editorDisplayLogicDAO.removeByOptionId(optionId);
            }
        }

        if(maxCol!=0) {
            List<EditorTitleOption> editorTitleOptionListColRow = new ArrayList<>();

            editorTitleOptionListColRow = editorTitleOptionDAO.queryEditorTitleOptionByColNum(maxCol, titleId);
            //大于当前行的，都做减1操作
            if (editorTitleOptionListColRow.size() > 0) {
                //循环获取选项，并选项号减1操作
                for (EditorTitleOption res : editorTitleOptionListColRow) {
                    EditorTitleOption req = new EditorTitleOption();
                    req.setOptionId(res.getOptionId());
                    req.setColNum(res.getColNum() - 1);
                    editorTitleOptionDAO.updateEditorTitleOptionColNumOrder(req.getOptionId(), req.getColNum());
                }
            }
            editorTitleOptionListColRow = editorTitleOptionDAO.queryEditorTitleOptionByRowNum(maxRow,titleId);
            //大于当前列的，都做减1操作
            if (editorTitleOptionListColRow.size() > 0) {
                //循环获取选项，并选项号减1操作
                for (EditorTitleOption res : editorTitleOptionListColRow) {
                    EditorTitleOption req = new EditorTitleOption();
                    req.setOptionId(res.getOptionId());
                    req.setRowNum(res.getRowNum() - 1);
                    editorTitleOptionDAO.updateEditorTitleOptionRowNumOrder(req.getOptionId(), req.getRowNum());
                }
            }

        }
    }
//
//    /**
//     * 修改选项号
//     * @param editorTitleOptionReq
//     */
//    @Override
//    public void updateOptionNum(EditorTitleOption editorTitleOptionReq) {
//        //选项号重排
//    }
//
    @Override
    public EditorQuestionnaireTitle selectTitleByPrimaryKey(String titleId) {
        return editorQuestionnaireTitleDAO.get(titleId);

    }

    /**
     * 获取表单详情
     * @param getQuestionnaireDetailRequest
     * @return
     */
    @Override
    public EditorQuestionnaireDetailRes getQuestionnaireDetail(GetQuestionnaireDetailRequest getQuestionnaireDetailRequest) {
        EditorQuestionnaireDetailRes detailRes = new EditorQuestionnaireDetailRes();
        if(CommonUtils.isNull(getQuestionnaireDetailRequest.getUserId())&&CommonUtils.isNotNull(getQuestionnaireDetailRequest.getUid())){
            getQuestionnaireDetailRequest.setUserId(getQuestionnaireDetailRequest.getUid());
        }
        //表单外观
        EditorQuestionnaireStyle questionnaireStyle =
                editorQuestionnaireStyleDAO.getByQidAndDeviceType(getQuestionnaireDetailRequest.getDeviceType(),getQuestionnaireDetailRequest.getQuestionnaireId());
        //表单详情
        EditorQuestionnaire questionnaire =
                editorQuestionnaireDAO.get(getQuestionnaireDetailRequest.getQuestionnaireId());

        if(CommonUtils.isNull(questionnaire)){
            return null;
        }
        if(questionnaire.getQuestionnaireState().equals((byte)3)){

        }


        try {
            copyProperties(questionnaire,detailRes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        detailRes.setQuestionnaireStyleRes(questionnaireStyle);
        //表单题目
        List<EditorQuestionnaireTitle> titles = editorQuestionnaireTitleDAO.queryEditorQuestionnaireTitleByQid(getQuestionnaireDetailRequest.getQuestionnaireId());

        //获取用户答题表主键
        String userInfoId = null;
        if (getQuestionnaireDetailRequest.getShowType() == 2) {
            if(CommonUtils.isNotNull(getQuestionnaireDetailRequest.getUserInfoId())) {
                EditorUserInfo userInfo = editorUserInfoDAO.get(getQuestionnaireDetailRequest.getUserInfoId());
                if (CommonUtils.isNotEmpty(userInfo)) {
                    userInfoId = userInfo.getUserInfoId();
                    detailRes.setCreateTime(userInfo.getWriteTime());
                    detailRes.setUserInfoId(userInfo.getUserInfoId());
                    if(CommonUtils.isNotNull(userInfo.getInvestigatorId())) {
                        detailRes.setInvestigatorId(userInfo.getInvestigatorId());
                    }
                    if(CommonUtils.isNotNull(userInfo.getInvestigatorName())) {
                        detailRes.setInvestigatorName(userInfo.getInvestigatorName());
                    }
                }
            }
        }
//        if(CommonUtils.isNotNull(questionnaire.getIfReuse())&&questionnaire.getIfReuse()==1 && getQuestionnaireDetailRequest.getShowType() == 1){
//           List< EditorUserInfo> userInfolist = editorUserInfoDAO.queryEditorUserInfoByUserId(getQuestionnaireDetailRequest.getUserId(),getQuestionnaireDetailRequest.getQuestionnaireId());
//            EditorUserInfo userInfo =new EditorUserInfo();
//            if(CommonUtils.isNotEmpty(userInfolist)){
//                userInfo=userInfolist.get(0);
//            }
//
//            if (CommonUtils.isNotEmpty(userInfo)) {
//                userInfoId = userInfo.getUserInfoId();
//            }
//            if(CommonUtils.isNotNull(getQuestionnaireDetailRequest.getUserInfoId())) {
//                userInfoId =getQuestionnaireDetailRequest.getUserInfoId();
//            }
//        }
        if(CommonUtils.isNull(getQuestionnaireDetailRequest.getUserInfoId())||getQuestionnaireDetailRequest.getUserInfoId().length()==0||getQuestionnaireDetailRequest.getUserInfoId().equals("null")) {
            if (CommonUtils.isNotNull(questionnaire.getIfToday()) || CommonUtils.isNotNull(questionnaire.getEffectiveTime())) {
                List<EditorUserInfo> userInfolist = editorUserInfoDAO.queryEditorUserInfoByUserId(getQuestionnaireDetailRequest.getUserId(), getQuestionnaireDetailRequest.getQuestionnaireId());
                EditorUserInfo userInfo = new EditorUserInfo();
                if (CommonUtils.isNotEmpty(userInfolist)) {
                    userInfo = userInfolist.get(0);

                    if (CommonUtils.isNotEmpty(userInfo)) {
                        Calendar c1 = Calendar.getInstance();
                        Calendar c2 = Calendar.getInstance();
                        c1.setTime(userInfo.getWriteTime());
                        c2.setTime(new Date());
                        int year1 = c1.get(Calendar.YEAR);
                        int month1 = c1.get(Calendar.MONTH) + 1;
                        int day1 = c1.get(Calendar.DAY_OF_MONTH);
                        int year2 = c2.get(Calendar.YEAR);
                        int month2 = c2.get(Calendar.MONTH) + 1;
                        int day2 = c2.get(Calendar.DAY_OF_MONTH);
                        Boolean editorFlag1 = false;
                        Boolean editorFlag2 = false;
                        if (CommonUtils.isNotNull(questionnaire.getIfToday())) {
                            if (questionnaire.getIfToday() == 1 && (day1 == day2 && year1 == year2 && month1 == month2)) {
                                editorFlag1 = true;
                            }
                        }
                        if (CommonUtils.isNotNull(questionnaire.getEffectiveTime())) {
                            c1.add(Calendar.HOUR, questionnaire.getEffectiveTime());
                            if (c2.before(c1)) {
                                editorFlag2 = true;
                            }
                        }
                        if (editorFlag1 == true || editorFlag2 == true) {
                            userInfoId = userInfo.getUserInfoId();
                            detailRes.setCreateTime(userInfo.getWriteTime());
                            detailRes.setUserInfoId(userInfo.getUserInfoId());
                            if (CommonUtils.isNotNull(userInfo.getInvestigatorId())) {
                                detailRes.setInvestigatorId(userInfo.getInvestigatorId());
                            }
                            if (CommonUtils.isNotNull(userInfo.getInvestigatorName())) {
                                detailRes.setInvestigatorName(userInfo.getInvestigatorName());
                            }
                        }
                    }
                }
            }
        }

        //题目的总分数
        BigDecimal totalGrade = new BigDecimal(0.00);
        List<String> titleIds = new ArrayList<>();
        if (CommonUtils.isNotEmpty(titles)) {
            List<EditorQuestionnaireTitleRes> titlesRes = new ArrayList<>();
            //总分数
            BigDecimal grade = new BigDecimal(0.00);
            List<String> titleList = new ArrayList<>();
            Integer pageSize=0;
            Integer pageNo=1;
            for (EditorQuestionnaireTitle title : titles) {
                EditorQuestionnaireTitleRes editorQuestionnaireTitleRes = new EditorQuestionnaireTitleRes();
                copyProperties(title,editorQuestionnaireTitleRes);
                if(CommonUtils.isNotEmpty(editorQuestionnaireTitleRes.getWidgetType())&&editorQuestionnaireTitleRes.getWidgetType()==10){
                    pageSize++;
                    editorQuestionnaireTitleRes.setTitleList(titleList);
                    editorQuestionnaireTitleRes.setPageNo(pageNo);
                    pageNo++;
                    titleList=new  ArrayList<>();
                }else{
                    titleList.add(editorQuestionnaireTitleRes.getTitleId());
                }
                List<String> optionIds = new ArrayList<>();

                if ( userInfoId != null) {
                    //获取答案

                    EditorAnswer editorAnswer = editorAnswerDAO.getEditorAnswerById(getQuestionnaireDetailRequest.getQuestionnaireId(),userInfoId,title.getTitleId());
                    if (CommonUtils.isNotEmpty(editorAnswer)) {
                        if(editorAnswer.getOptionType().equals((byte)4)){
                            if(CommonUtils.isNotNull(editorAnswer.getAnswerContent())) {
                                EditorDict editorDict = editorDictDAO.get(editorAnswer.getAnswerContent());
                                if(null != editorDict){
                                    editorAnswer.setAnswerDesc(editorDict.getDictName());
                                }
                            }
                        }
                        //加答案
                        editorQuestionnaireTitleRes.setEditorAnswer(editorAnswer);

                        //分数统计 1单选题、2多选题、3下拉选、4字典选、5级联选择、6单项填空、7多项填空、8文件上传、9表格矩阵、10分页、11分割线、12备注说明
                        if (editorAnswer.getOptionType() != null) {
                            if (editorAnswer.getOptionType() == 1 || editorAnswer.getOptionType() == 3) {
                                //根据单个选项id获取选项分值
                                optionIds.add(editorAnswer.getOptionId());
                                List<EditorTitleOption> options = editorTitleOptionDAO.queryEditorTitleOptionByOptionIds(optionIds);
                                if (options.size()!=0&&options.get(0).getOptionGrade() != null) {
                                    grade = grade.add(options.get(0).getOptionGrade());
                                }
                            } else if (editorAnswer.getOptionType() == 2 || editorAnswer.getOptionType() == 7) {
                                //根据多个选项id获取选项分值
                                optionIds.add(editorAnswer.getOptionId());
                                List<EditorTitleOption> options = editorTitleOptionDAO.queryEditorTitleOptionByOptionIds(optionIds);
                                for (EditorTitleOption option : options) {
                                    if (option.getOptionGrade() != null) {
                                        grade = grade.add(option.getOptionGrade());
                                    }
                                }
                            } else if (editorAnswer.getOptionType() == 6 || editorAnswer.getOptionType() == 4 || editorAnswer.getOptionType() == 12) {
                                //获取题目分值
                                if (!"".equals(editorAnswer.getAnswerContent())) {
                                    if(CommonUtils.isNotNull(title.getOptionGrade())) {
                                        grade = grade.add(title.getOptionGrade());
                                    }
                                }
                            }
                        }
                    }
                }
                //跳题设置
                List<EditorSkipLogic> editorSkipLogics = editorSkipLogicDAO.queryEditorSkipLogicListByTitleId(title.getTitleId());
                editorQuestionnaireTitleRes.setEditorSkipLogic(editorSkipLogics);

                //显示设置

                List<EditorDisplayLogic> editorDisplayLogics = editorDisplayLogicDAO.queryEditorDisplayLogicListByTitleId(title.getTitleId());
                editorQuestionnaireTitleRes.setEditorDisplayLogic(editorDisplayLogics);

                titlesRes.add(editorQuestionnaireTitleRes);
                titleIds.add(title.getTitleId());
            }
            detailRes.setPageSize(pageSize);
            detailRes.setGrade(grade);
            detailRes.setTitles(titlesRes);
            //题目选项
            List<EditorTitleOption> options = editorTitleOptionDAO.queryEditorTitleOptionByTitleIds(titleIds);
            if (CommonUtils.isNotEmpty(options)) {
                Map<String, List<EditorTitleOption>> map = new HashMap<>(options.size());
                for (EditorTitleOption option : options) {
                    EditorTitleOption optionRes = new EditorTitleOption();
                    copyProperties(option,optionRes);
                    if (map.containsKey(option.getTitleId())) {
                        List<EditorTitleOption> resList = map.get(option.getTitleId());
                        resList.add(optionRes);
                    } else {
                        List<EditorTitleOption> resList = new ArrayList<>();
                        resList.add(optionRes);
                        map.put(optionRes.getTitleId(), resList);
                    }
                }
                for (EditorQuestionnaireTitleRes titleRes : titlesRes) {

//                    titleRes.setOptions(map.get(titleRes.getTitleId()));
                    List<EditorTitleOption> resList = map.get(titleRes.getTitleId());
                    if (CommonUtils.isNotEmpty(resList)) {
                        try {
                            resList.sort(new Comparator<EditorTitleOption>() {
                                @Override
                                public int compare(EditorTitleOption o1, EditorTitleOption o2) {
                                    return o1.getOptionNum().compareTo(o2.getOptionNum());
                                }
                            });
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        titleRes.setOptions(resList);
                    }
                    //分数统计 1单选题、2多选题、3下拉选、4字典选、5级联选择、6单项填空、7多项填空、8文件上传、9表格矩阵、10分页、11分割线、12备注说明
                    if (titleRes.getWidgetType() != null) {
                        if (titleRes.getWidgetType() == 1 || titleRes.getWidgetType() == 3 || titleRes.getWidgetType() == 14 || titleRes.getWidgetType() == 26 || titleRes.getWidgetType() == 29 || titleRes.getWidgetType() == 30) {
                            BigDecimal  max = new BigDecimal(0.00);
                            if(CommonUtils.isNotEmpty(resList)){
                                for (EditorTitleOption editorTitleOption : resList) {
                                    if (CommonUtils.isNotEmpty(editorTitleOption.getOptionGrade())) {
                                        int result = max.compareTo(editorTitleOption.getOptionGrade());
                                        if (result < 0) {
                                            max = editorTitleOption.getOptionGrade();
                                        }
                                    }
                                }
                            }
                            totalGrade = totalGrade.add(max);
                        } else if (titleRes.getWidgetType() == 2 || titleRes.getWidgetType() == 7) {
                            if (CommonUtils.isNotEmpty(resList)){
                                for (EditorTitleOption editorTitleOption : resList) {
                                    if (CommonUtils.isNotEmpty(editorTitleOption.getOptionGrade())) {
                                        totalGrade =  totalGrade.add(editorTitleOption.getOptionGrade());
                                    }
                                }
                            }
                        } else if (titleRes.getWidgetType() == 6 && "99".equals(titleRes.getWriteTips())) {
                            if (CommonUtils.isNotEmpty(titleRes.getStartMark())){
                                double startMark = Double.valueOf(titleRes.getStartMark());
                                String answerContent = titleRes.getStartTotal();
                                Pattern pattern = Pattern.compile("^(\\-|\\+)?\\d+(\\.\\d+)?$");
                                Matcher isNum = pattern.matcher(answerContent);
                                if (CommonUtils.isNotEmpty(answerContent) && isNum.matches()) {
                                    double answer= Double.valueOf(answerContent);
                                    double i = startMark * answer;
                                    totalGrade = totalGrade.add(new BigDecimal(i));
                                } else {
                                    totalGrade = totalGrade.add(new BigDecimal(0));
                                }
                            }
                        }
                    }
                }
            }
        }
        detailRes.setTotalGrade(totalGrade);
        return detailRes;
    }

    @Override
    public BaseResponse queryQuestionnaireTitleList(EditorQuestionnaireTitle docQuestionnaireListReq) {
        QueryEditorTitleListResponse queryEditorTitleListResponse=new QueryEditorTitleListResponse();
        queryEditorTitleListResponse.setList(editorQuestionnaireTitleDAO.queryEditorQuestionnaireTitleByQid(docQuestionnaireListReq.getQuestionnaireId()));
        queryEditorTitleListResponse.setTotal(editorQuestionnaireTitleDAO.queryEditorTitleCount(docQuestionnaireListReq.getQuestionnaireId()));
        BaseResponse<QueryEditorTitleListResponse> baseResponse = new BaseResponse<>();
        baseResponse.setData(queryEditorTitleListResponse);
        return  baseResponse;
    }


    @Override
    public BaseResponse queryQuestionnaireOptionList(EditorTitleOption docQuestionnaireListReq) {
        QueryEditorOptionListResponse queryEditorOptionListResponse=new QueryEditorOptionListResponse();
        EditorQuestionnaireTitle editorQuestionnaireTitle=editorQuestionnaireTitleDAO.get(docQuestionnaireListReq.getTitleId());
        if(editorQuestionnaireTitle.getWidgetType().equals((byte)4)){
            EditorDict editorDict=editorDictDAO.get(editorQuestionnaireTitle.getDictId());
            List<EditorTitleOption> editorTitleOptionList = new ArrayList<>();
            EditorTitleOption editorTitleOption=new EditorTitleOption();
            if(CommonUtils.isNotNull(editorDict)){
            editorTitleOptionList.add(editorTitleOption);
            editorTitleOptionList.get(0).setOptionId(editorDict.getDictId());
            editorTitleOptionList.get(0).setOptionContent(editorDict.getDictName());
            editorTitleOptionList.get(0).setTitleId(docQuestionnaireListReq.getTitleId());
            queryEditorOptionListResponse.setList(editorTitleOptionList);
            queryEditorOptionListResponse.setTotal((long)1);
            }
        }else {
            queryEditorOptionListResponse.setList(editorTitleOptionDAO.queryEditorOptionByTitleId(docQuestionnaireListReq));
            queryEditorOptionListResponse.setTotal(editorTitleOptionDAO.queryEditorOptionCount(docQuestionnaireListReq));
        }
        BaseResponse<QueryEditorOptionListResponse> baseResponse = new BaseResponse<>();
        baseResponse.setData(queryEditorOptionListResponse);
        return  baseResponse;
    }


    /**
     * @description: 查询收藏题目列表
     * @author: chenJij@bsoft.com.cn
     * @date: 2021/10/12 1:26
     * @param: req
     * @return: java.util.List<com.bsoft.gol.editor.editor.response.QueryCollectionListResponse>
     */
    @Override
    public List<QueryCollectionListResponse> queryCollectionList(QueryCollectionListRequest req) {
        return editorQuestionnaireTitleCollectionDAO.queryEditorQuestionnaireList(req);
    }


    /**
     * @description: 收藏问卷题目
     * @author: chenJij@bsoft.com.cn
     * @date: 2021/10/12 13:05
     * @param: req
     * @return: void
     */
    @Override
    public void collectTitle(CollectTitleRequest req) throws ControllerException {
        if(CommonUtils.isEmpty(req.getTitleId())){
            throw new ControllerException("问卷题目标识不能为空");
        }
        if(CommonUtils.isEmpty(req.getUserId())){
            throw new ControllerException("当前登录用户标识不能为空");
        }

        //复制题目，新增
        EditorQuestionnaireTitle editorQuestionnaireTitle = editorQuestionnaireTitleDAO.get(req.getTitleId());
        if(null != editorQuestionnaireTitle){
            String titleId = editorQuestionnaireTitle.getTitleId();
            editorQuestionnaireTitle.setTitleId(UUID.randomUUID().toString());
            editorQuestionnaireTitle.setCreateTime(new Date());
            //收藏的题目没有问卷标识
            editorQuestionnaireTitle.setQuestionnaireId(null);
            editorQuestionnaireTitleDAO.save(editorQuestionnaireTitle);

            //复制题目选项
            List<EditorTitleOption> editorTitleOptions = editorTitleOptionDAO.queryEditorTitleOptionByTitleId(titleId);
            if(CommonUtils.isNotEmpty(editorTitleOptions)){
                for (EditorTitleOption editorTitleOption : editorTitleOptions) {
                    String optionId = editorTitleOption.getOptionId();
                    editorTitleOption.setOptionId(UUID.randomUUID().toString());
                    editorTitleOption.setTitleId(editorQuestionnaireTitle.getTitleId());
                    editorTitleOption.setCreateTime(new Date());
                    editorTitleOptionDAO.save(editorTitleOption);

                    //复制选项逻辑
                    List<EditorDisplayLogic> editorDisplayLogics = editorDisplayLogicDAO.queryEditorDisplayLogicListByOptionId(titleId, optionId);
                    if(CommonUtils.isNotEmpty(editorDisplayLogics)){
                        for (EditorDisplayLogic editorDisplayLogic : editorDisplayLogics) {
                            editorDisplayLogic.setDisplayId(UUID.randomUUID().toString());
                            editorDisplayLogic.setOptionId(editorTitleOption.getOptionId());
                            editorDisplayLogic.setTitleId(editorQuestionnaireTitle.getTitleId());
                            editorDisplayLogic.setCreateTime(new Date());
                            editorDisplayLogicDAO.save(editorDisplayLogic);
                        }
                    }

                    //复制跳题逻辑
                    List<EditorSkipLogic> editorSkipLogics = editorSkipLogicDAO.queryEditorSkipLogicListByOptionId(titleId, optionId);
                    if(CommonUtils.isNotEmpty(editorSkipLogics)){
                        for (EditorSkipLogic editorSkipLogic : editorSkipLogics) {
                            editorSkipLogic.setSkipId(UUID.randomUUID().toString());
                            editorSkipLogic.setOptionId(editorTitleOption.getOptionId());
                            editorSkipLogic.setTitleId(editorQuestionnaireTitle.getTitleId());
                            editorSkipLogic.setCreateTime(new Date());
                            editorSkipLogicDAO.save(editorSkipLogic);
                        }
                    }
                }
            }

            //题目与收藏人关系
            EditorQuestionnaireTitleCollection editorQuestionnaireTitleCollection = new EditorQuestionnaireTitleCollection();
            editorQuestionnaireTitleCollection.setCollectionId(UUID.randomUUID().toString());
            editorQuestionnaireTitleCollection.setCollectorId(req.getUserId());
            editorQuestionnaireTitleCollection.setTitleId(editorQuestionnaireTitle.getTitleId());
            editorQuestionnaireTitleCollection.setTitleName(editorQuestionnaireTitle.getTitleName());
            editorQuestionnaireTitleCollection.setSort(0);
            editorQuestionnaireTitleCollection.setCreateTime(new Date());
            editorQuestionnaireTitleCollection.setCreateUserId(req.getUserId());
            editorQuestionnaireTitleCollectionDAO.save(editorQuestionnaireTitleCollection);
        }
    }


    /**
     * @description: 删除收藏题目
     * @author: chenJij@bsoft.com.cn
     * @date: 2021/10/12 13:15
     * @param: req
     * @return: void
     */
    @Override
    public void cancelCollection(CollectTitleRequest req) {
        if(CommonUtils.isNotEmpty(req.getCollectionId())){
            EditorQuestionnaireTitleCollection editorQuestionnaireTitleCollection = editorQuestionnaireTitleCollectionDAO.get(req.getCollectionId());
            if(null != editorQuestionnaireTitleCollection){
                //删除所有题目
                editorQuestionnaireTitleDAO.remove(editorQuestionnaireTitleCollection.getTitleId());
                //删除所有选项
                editorTitleOptionDAO.removeByTitleId(editorQuestionnaireTitleCollection.getTitleId());
                //删除所有选项逻辑
                editorDisplayLogicDAO.removeByTitleId(editorQuestionnaireTitleCollection.getTitleId());
                //删除收藏题目
                editorQuestionnaireTitleCollectionDAO.remove(editorQuestionnaireTitleCollection.getCollectionId());
                //删除跳题逻辑
                editorSkipLogicDAO.removeByTitleId(editorQuestionnaireTitleCollection.getTitleId());
            }
        }
    }

    /**
     * @description: 通过题目id获取题目选项列表
     * @author: chenJij@bsoft.com.cn
     * @date: 2022/7/29 9:55
     * @param: titleId
     * @return: java.util.List<com.bsoft.gol.editor.editor.EditorTitleOption>
     */
    @Override
    public List<EditorTitleOption> queryEditorTitleOptionList(String titleId){
        List<EditorTitleOption> optionList =  editorTitleOptionDAO.queryEditorTitleOptionByTitleId(titleId);
        return optionList;
    }

}